<template>
  <view>
    <leeLoading
      :animateTxt="leeLoading.animateTxt"
      :loadTxt="leeLoading.loadTxt"
      :type="leeLoading.type"
      :shadowBg="leeLoading.shadowBg"
      :show="leeLoading.show"
    ></leeLoading>
    <view
      class="left_right_control"
      v-if="Type < 5"
    >
      <view class="left-home">
        <uni-data-select
          class="store-select"
          v-model="versionId"
          :localdata="range"
          placeholder="请选择版本号"
          @change="change"
          :clear="false"
        ></uni-data-select>
      </view>
    </view>
    <view class="upgrade_set">
      <l-circularProgress
        progressColor="#FFA36F"
        :lineWidth="10"
        fontSize="16"
        boxWidth="110"
        boxHeight="110"
        fontColor="#000"
        gradualColor="#FF8140"
        :percent="upgradeData.Progress"
      >
      </l-circularProgress>
      <button
        class="mini-btn"
        round
        size="mini"
        type="primary"
        :disabled="disable"
        @tap="updateUpgrade"
      >
        {{ btnName }}
      </button>
      <view
        class="erroTishi"
        v-if="Type == 2 || Type == 3"
      >
        <view class="textTishi"
          >下载成功后需要40左右秒时间重启<br />
          请勿断电，耐心等待...</view
        >
      </view>
    </view>
  </view>
</template>

<script>
  const CmdType = {
    APPSendOTAPackage: 14,
  }
  import leeLoading from '../../components/StarLee-loading/leeLoading.vue'
  import parsingData from '../../util/parsingData'
  import getPrefixAndControl from '../../util/getPrefixAndControl'
  import { MQTT_IP, MQTT_OPTIONS } from '@/utils/mqtt.js'
  var Paho = require('../../../utils/paho-mqtt')
  export default {
    components: {
      leeLoading,
    },
    data() {
      return {
        leeLoading: {
          show: false,
          type: 'rotate3',
          shadowBg: '',
          animateTxt: true,
          loadTxt: '',
        },
        indexAllData: null,
        isRendering: false, //防止重复点击
        equipmentNo: uni.getStorageSync('equipmentNo'), //uni.getStorageSync("equipmentNo"),
        equipmentTypeId: uni.getStorageSync('equipmentTypeId'), //uni.getStorageSync("equipmentTypeId"),
        realTime: null,
        client: null,
        timer: null,
        timers: null,
        timeout: null,
        btnName: '',
        upgradeData: '',
        subTopic: uni.getStorageSync('subTopic'),
        Type: '',
        versionId: 0,
        versionName: '',
        range: [],
        disable: false,
      }
    },
    onLoad(option) {
      this.Type = option.Type
      if (option.Type == 2) {
        uni.setNavigationBarTitle({
          title: '软件升级',
        })
        this.btnName = '软件升级'
      } else if (option.Type == 3) {
        uni.setNavigationBarTitle({
          title: 'Logo升级',
        })
        this.btnName = 'logo升级'
      } else if (option.Type == 4) {
        uni.setNavigationBarTitle({
          title: '资源升级',
        })
        this.btnName = '资源下载'
      } else if (option.Type == 5) {
        uni.setNavigationBarTitle({
          title: '固件升级',
        })
        this.btnName = '固件下载'
      }
      uni.showLoading({ title: '数据加载中...', mask: true })
      this.getIndexData()
      //延迟一秒钟去获取数据
      setTimeout(async () => {
        //链接mqtt
        this.connect()
      }, 1000)
      //15秒后没关闭就自动关闭
      this.timer = setTimeout(() => {
        uni.hideLoading()
      }, 15000)
    },
    // 组件销毁时关闭定时器
    beforeDestroy() {
      clearTimeout(this.timer)
    },
    methods: {
      change(e) {
        this.versionId = e
      },
      getIndexData() {
        this.realTime = setInterval(async () => {
          const data = {
            Type: 1,
            Version: 0,
            Stage: 0,
            Progress: 0,
            Resu1t: 0,
          }
          //进入界面链接mqtt后自动订阅
          const res = await getPrefixAndControl.controlCmd(
            this.equipmentTypeId,
            this.equipmentNo,
            CmdType.APPSendOTAPackage,
            data
          )
          if (res.code != 200) {
            this.$modal.msgError('下发失败')
            clearInterval(this.realTime)
            uni.hideLoading()
          }
        }, 2000)
      },
      //链接方法
      connect() {
        try {
          const thant = this
          thant.client = new Paho.Client(
            MQTT_IP,
            'SERVER_' +
              Math.floor(Math.random() * 999) +
              1 +
              '_' +
              thant.equipmentNo
          )
          //后面这个字符串可以用一个随机字符串方法随机生成
          var connectOptions = {
            timeout: MQTT_OPTIONS.timeout,
            useSSL: MQTT_OPTIONS.useSSL,
            cleanSession: MQTT_OPTIONS.cleanSession, //实现QoS>0必须设置为false，代表不清除，是持久会话
            keepAliveInterval: MQTT_OPTIONS.keepAliveInterval,
            reconnect: MQTT_OPTIONS.reconnect, //意外断开之后会重连，第一次1秒后重连，往后每次翻倍直到2分钟，后续保持2分钟
            mqttVersion: MQTT_OPTIONS.mqttVersion,
            userName: MQTT_OPTIONS.username,
            password: MQTT_OPTIONS.password,
            onSuccess: function () {
              thant.client.onMessageArrived = function (msg) {
                const data = JSON.parse(
                  msg.payloadString.replace(/\u0000*$/, '')
                )
                if (data != null) {
                  data.Data.forEach((item, index) => {
                    if (item.Cmd == 9) {
                      thant.indexAllData = parsingData.getNumBycommand(
                        item.Cmd,
                        item.Value
                      )
                      if (thant.indexAllData.communicationState != 1) {
                        thant.$modal.msgError('通讯错误')
                        clearInterval(this.realTime)
                        uni.stopPullDownRefresh()
                        uni.hideLoading({
                          noConflict: true,
                        })
                        return
                      }
                    }
                    if (item.Cmd == 14) {
                      thant.upgradeData = parsingData.getNumBycommand(
                        item.Cmd,
                        item.Value
                      )
                      if (thant.upgradeData !== '') {
                        if (thant.range.length == 0) {
                          thant.upgradeData.Version.forEach((item, index) => {
                            thant.range.push({
                              text:
                                (item >> 6) +
                                '.' +
                                ((item >> 4) & 0x03) +
                                '.' +
                                (item & 0x0f),
                              value: item,
                            })
                          })
                        }
                        //清除数据
                        thant.empty()
                        uni.hideLoading()
                      }
                      if (
                        thant.upgradeData.Type == 4 ||
                        thant.upgradeData.Type == 5
                      ) {
                        if (thant.upgradeData.Stage == 1) {
                          if (
                            thant.upgradeData.Progress < 100 &&
                            thant.upgradeData.Result == false
                          ) {
                            thant.disable = true
                            thant.btnName = '下载中'
                          } else if (
                            thant.upgradeData.Progress == 100 &&
                            thant.upgradeData.Result == false
                          ) {
                            thant.disable = false
                            uni.navigateBack({
                              delta: 1,
                              success() {
                                thant.$modal.msgError('下载失败')
                              },
                            })
                          }
                        } else {
                          if (
                            thant.upgradeData.Progress < 100 &&
                            thant.upgradeData.Result == false
                          ) {
                            thant.disable = true
                            thant.btnName = '升级中'
                          } else if (
                            thant.upgradeData.Progress == 100 &&
                            thant.upgradeData.Result == false
                          ) {
                            uni.navigateBack({
                              delta: 1,
                              success() {
                                thant.$modal.msgError('升级失败')
                              },
                            })
                          } else if (
                            thant.upgradeData.Progress == 100 &&
                            thant.upgradeData.Result == true
                          ) {
                            uni.navigateBack({
                              delta: 1,
                              success() {
                                thant.$modal.msgSuccess('升级成功')
                              },
                            })
                          }
                        }
                      } else {
                        if (
                          thant.upgradeData.Progress < 100 &&
                          thant.upgradeData.Result == false
                        ) {
                          thant.disable = true
                          thant.btnName = '下载中'
                        } else if (
                          thant.upgradeData.Progress == 100 &&
                          thant.upgradeData.Result == false
                        ) {
                          uni.navigateBack({
                            delta: 1,
                            success() {
                              thant.$modal.msgError('下载失败')
                            },
                          })
                        } else if (
                          thant.upgradeData.Progress == 100 &&
                          thant.upgradeData.Result == true
                        ) {
                          if (thant.upgradeData.Stage == 1) {
                            thant.btnName = '重启中'
                            thant.leeLoading.show = true
                            thant.leeLoading.loadTxt = '设备重启中'
                            //一分钟还是没收到消息就关闭
                            thant.timers = setTimeout(() => {
                              uni.navigateBack({
                                delta: 1,
                                success() {
                                  thant.$modal.msgError('升级失败')
                                  thant.leeLoading.show = false
                                },
                              })
                            }, 50000)
                          } else {
                            uni.reLaunch({
                              url: '../../index/index',
                              success() {
                                thant.leeLoading.show = false
                                thant.$modal.msgSuccess('升级成功')
                              },
                            })
                          }
                        }
                      }
                    }
                  })
                }
              }
              thant.client.subscribe(thant.subTopic, {
                qos: 1,
              })
            },
            onFailure: function (option) {
              uni.showToast({
                title: option,
                icon: 'error',
              })
            },
          }
          this.client.connect(connectOptions)
        } catch (error) {
          this.$modal.msgError('连接错误')
        }
      },

      //固件升级点击操作
      updateUpgrade: async function () {
        if (this.versionId == '' && this.Type != 5) {
          this.$modal.msgError('请选择版本号')
        } else {
          const data = {
            Type: parseInt(this.Type),
            Version: this.versionId,
            Stage: 0,
            Progress: 0,
            Resu1t: 0,
          }
          //点击开启加载
          this.loadingClick()
          const res = await getPrefixAndControl.controlCmd(
            this.equipmentTypeId,
            this.equipmentNo,
            CmdType.APPSendOTAPackage,
            data
          )
          if (res.code != 200) {
            this.$modal.msgError('下发失败')
          }
        }
      },
      loadingClick() {
        const thant = this
        thant.leeLoading.show = true
        thant.timeout = setTimeout(function () {
          thant.leeLoading.show = false
          thant.$modal.msgError('操作未成功')
        }, 5000)
      },
      //清除
      empty() {
        clearInterval(this.realTime)
        clearTimeout(this.timeout)
        this.leeLoading.show = false
      },
    },
    onUnload() {
      clearInterval(this.realTime)
      clearTimeout(this.timers)
      clearTimeout(this.timer)
      if (this.client != null) {
        this.client.disconnect()
        this.client = null
      }
    },
  }
</script>

<style>
  page {
    background-color: #f6f6f6;
  }
  .upgrade_set {
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    margin-top: 100rpx;
  }
  .left-home {
    margin-left: 30rpx;
    width: 300rpx;
  }
  .erroTishi {
    color: red;
    margin-top: 20rpx;
  }
  .textTishi {
    display: block;
    text-align: center;
  }
</style>
